package com.hsyt.pfc.core.queue;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.Arrays;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedTransferQueue;

/**
 * @Description:
 * @ClassName: WaitingQueue
 * @Package: com.hsyt.pfc.core.queue
 * @Author: wangze@hsyuntai.com
 * @Date: 2018年9月30日 9:40
 * @Copyright: 版权归 HSYUNTAI 所有
 */
public class WaitingQueue implements Runnable {

    private static final Logger LOGGER = LoggerFactory.getLogger(WaitingQueue.class);

    private static WaitingQueueListener listener;

    private static BlockingQueue<WaitingQueueTask> waitingQueueTasks;

    private static final Boolean STATE = true;

    public WaitingQueue() {
        listener = new SimpleWaitingQueueListener();
        waitingQueueTasks = new LinkedTransferQueue<>();
    }

    public WaitingQueueTask createTask(Object target, String method, Object... args) throws InterruptedException {
        WaitingQueueTask task = null;
        if (null == args) {
            task = new WaitingQueueTask(target, method);
        } else {
            task = new WaitingQueueTask(target, method, Arrays.asList(args));
        }
        try {
            waitingQueueTasks.put(task);
        } catch (InterruptedException e) {
            throw e;
        }
        return task;
    }

    public WaitingQueueTask createTask(WaitingQueueTask task) throws InterruptedException {
        try {
            waitingQueueTasks.put(task);
        } catch (InterruptedException e) {
            throw e;
        }
        return task;
    }

    @Override
    public void run() {
        while (STATE) {
            try {
                listener.onCreate(waitingQueueTasks.take());
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }

    public int getActive() {
        return waitingQueueTasks.size();
    }

}
